﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CefSharp;
using CefSharp.Wpf;
using Newtonsoft.Json;
using Newtonsoft;
using Microsoft.Win32;

namespace DataAnalyse
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            initMenu();
            AppStatic.isLoginOut = false;
            this.Loaded += MainWindow_Loaded;
            this.Closing += MainWindow_Closing;
        }

        private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (!AppStatic.isLoginOut)
            {
                DataAnalyseClient.CloseDialogWindow closeWindow = new DataAnalyseClient.CloseDialogWindow();
                bool? result = closeWindow.ShowDialog();
                if (result == null ? false : Convert.ToBoolean(result))
                {
                    e.Cancel = false;
                    this.DialogResult = true;
                }
                else
                {
                    e.Cancel = true;
                }
            }
            else
            {
                this.DialogResult = true;
            }
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            MenuItemViewModel menuItem = new MenuItemViewModel();
            menuItem.id = 0;
            menuItem.name = "首页";
            menuItem.url = AppStatic.BaseUrl;
            addTab(menuItem);
        }

        private void menu_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabItem tab = null;
            MenuItemViewModel menuItem = e.AddedItems[0] as MenuItemViewModel;
            foreach(var item in this.tab.Items)
            {
                TabItem tabItem = item as TabItem;
                if (tabItem.TabIndex == menuItem.id)
                {
                    tab = tabItem;
                    break;
                }
            }
            if (tab != null)
            {
                tab.IsSelected = true;
            }
            else
            {
                addTab(menuItem);
            }
            
        }

        void addTab(MenuItemViewModel menuItem)
        {
            TabItem tab = new TabItem();
            tab.Tag = menuItem;
            tab.Header = menuItem.name;
            tab.TabIndex = menuItem.id;
            ChromiumWebBrowser webBrowser = new ChromiumWebBrowser();
            //webBrowser.FrameLoadEnd += (s, eve) =>
            //{
            //    var browser = webBrowser.GetBrowser();
            //    browser.ShowDevTools();
            //};
            webBrowser.JavascriptObjectRepository.ResolveObject+=(s, eve) =>
            {
                var repo = eve.ObjectRepository;
                if (eve.ObjectName == "clientAddNewTab") //这个名字对应页面上 CefSharp.BindObjectAsync 部分
                {
                    repo.Register("clientAddNewTab", new ScriptCallbackManager(this.tab), isAsync: true, options: BindingOptions.DefaultBinder);
                }
            };
            tab.Content = webBrowser;
            tab.IsSelected = true;
            this.tab.Items.Add(tab);
            webBrowser.Address = menuItem.url;
        }

        private void Image_MouseDown(object sender, MouseButtonEventArgs e)
        {
            this.WindowState = WindowState.Minimized;
        }

        private void Image_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            this.Close();
        }

        void initMenu()
        {
            var rootElements = AppStatic.Menu.FindAll(x => x.pid == 0).OrderBy(x => x.order);
            foreach(var item in rootElements)
            {
                MenuItem menuItem = new MenuItem();
                menuItem.Header = item.name;
                menuItem.Tag = item;
                menuItem.Click += MenuItem_Click;
                initChildMenu(menuItem,item);
                this.menu.Items.Add(menuItem);
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            MenuItem menuItem = sender as MenuItem;
            MenuItemViewModel vm = menuItem.Tag as MenuItemViewModel;
            if (vm.url == null)
            {
                return;
            }
            else
            {
                addTab(vm);
                e.Handled = true;
            }
        }

        void initChildMenu(MenuItem menuItem,MenuItemViewModel itemViewModel)
        {
            var childElement = AppStatic.Menu.FindAll(x => x.pid == itemViewModel.id).OrderBy(x=>x.order);
            foreach (var item in childElement)
            {
                MenuItem childItem = new MenuItem();
                childItem.Header = item.name;
                childItem.Tag = item;
                childItem.Click += MenuItem_Click;
                initChildMenu(childItem,item);
                menuItem.Items.Add(childItem);
            }
        }

        private void test_Click(object sender, RoutedEventArgs e)
        {
            TabItem current = this.tab.SelectedItem as TabItem;
            ChromiumWebBrowser we = current.Content as ChromiumWebBrowser;
            var cookieManager = we.GetCookieManager();
            CookieVisitor cookieVisitor = new CookieVisitor();
            cookieVisitor.SendCookie += visitor_SendCookie;
            cookieManager.VisitAllCookies(cookieVisitor);
        }
        private void visitor_SendCookie(CefSharp.Cookie obj)
        {
            string ds = obj.Domain.TrimStart('.') + "^" + obj.Name + "^" + obj.Value + "$" ;
            Debug.WriteLine(ds);
        }

        private void btnPerson_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MenuItemViewModel menuItem = new MenuItemViewModel();
            menuItem.id = 65536;
            menuItem.name = "个人中心";
            menuItem.url = AppStatic.PersonUrl;
            addTab(menuItem);
        }

        private void btnExit_MouseDown(object sender, MouseButtonEventArgs e)
        {
            AppStatic.isLoginOut = true;
            this.Close();
        }
    }
    // <summary>
    /// js调用方法类
    /// </summary>
    [System.Runtime.InteropServices.ComVisible(true)]
    class ScriptCallbackManager
    {
        private DataTabControl dataTabControl;
        public ScriptCallbackManager(DataTabControl tabControl)
        {
            this.dataTabControl = tabControl;
        }
        /// <summary>
        /// 关闭窗体
        /// </summary>
        public void addClientTab(string jsonString)
        {
            MenuItemViewModel menuItem = JsonConvert.DeserializeObject<MenuItemViewModel>(jsonString);
            this.dataTabControl.Dispatcher.Invoke(() =>
            {
                TabItem tab = null;
                foreach (var item in this.dataTabControl.Items)
                {
                    TabItem tabItem = item as TabItem;
                    if (tabItem.TabIndex == menuItem.id)
                    {
                        tab = tabItem;
                        break;
                    }
                }
                if (tab != null)
                {
                    tab.IsSelected = true;
                }
                else
                {
                    addTab(menuItem);
                }
            });
        }
        void addTab(MenuItemViewModel menuItem)
        {
            TabItem tab = new TabItem();
            tab.Tag = menuItem;
            tab.Header = menuItem.name;
            tab.TabIndex = menuItem.id;
            ChromiumWebBrowser webBrowser = new ChromiumWebBrowser();
            webBrowser.JavascriptObjectRepository.ResolveObject += (s, eve) =>
            {
                var repo = eve.ObjectRepository;
                if (eve.ObjectName == "clientAddNewTab") //这个名字对应页面上 CefSharp.BindObjectAsync 部分
                {
                    repo.Register("clientAddNewTab", new ScriptCallbackManager(this.dataTabControl), isAsync: true, options: BindingOptions.DefaultBinder);
                }
            };
            tab.Content = webBrowser;
            tab.IsSelected = true;
            this.dataTabControl.Items.Add(tab);
            webBrowser.Address = menuItem.url;
        }

        public void downloadIndexData(string[] ids)
        {
            this.dataTabControl.Dispatcher.Invoke(() =>
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.FileName = "数据下载-"+DateTime.Now.ToString("yyyMMdd")+".xlsx";
                dialog.Filter = "Excel files(*.xls)|*.xls|All files(*.*)|*.*";
                if (dialog.ShowDialog().Value)
                {
                    AppStatic.restUtils.downExcel(ids, dialog.FileName);
                }
            });
        }
    }

 public class CookieVisitor : CefSharp.ICookieVisitor
    {
        public event Action<CefSharp.Cookie> SendCookie;

        public void Dispose()
        {
            
        }

        public bool Visit(CefSharp.Cookie cookie, int count, int total, ref bool deleteCookie)
        {
            deleteCookie = false;
            if (SendCookie != null)
            {
                SendCookie(cookie);
            }

            return true;
        }
        

    }
}
